package org.apache.rocketmq.example.quickstart.sort;

import jdk.nashorn.internal.objects.annotations.Getter;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 部分顺序消息生产者
 */
public class InOrderProducer {
    public static void main(String[] args) {
        // 创建生产者
        DefaultMQProducer producer = new DefaultMQProducer("message-group-4");
        // 设置nameServer地址
        producer.setNamesrvAddr("39.107.66.31:9876");
        // 启动生产者
        try {
            producer.start();
            // 发送消息
            for (Order order : buildOrderList()) {
                // 创建消息实体
                Message message = new Message("message-topic-6", null, order.toString().getBytes(RemotingHelper.DEFAULT_CHARSET));
                // 发送消息-单向发送
                // 指定消息体,队列选择器,选择器参数(订单id)
                producer.sendOneway(message, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        // 通过取模确定相同id的订单数据发送到同一个消息队列中
                        return mqs.get((Integer) arg % mqs.size());
                    }
                }, order.getOrderId());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 停止生产者
            producer.shutdown();
        }
    }

    // 创建Order类
    public static class Order {

        private final Integer orderId;

        private final String step;

        public Order(Integer orderId, String step) {
            this.orderId = orderId;
            this.step = step;
        }

        public Integer getOrderId() {
            return orderId;
        }

        public String getStep() {
            return step;
        }

        @Override
        public String toString() {
            return "Order{" +
                    "orderId=" + orderId +
                    ", step='" + step + '\'' +
                    '}';
        }
    }

    // 构造消息列表
    // 4个订单 3个步骤
    private static List<Order> buildOrderList() {
        List<Order> orderList = new ArrayList<>();

        orderList.add(new Order(1, "创建"));
        orderList.add(new Order(2, "创建"));
        orderList.add(new Order(3, "创建"));
        orderList.add(new Order(4, "创建"));

        orderList.add(new Order(4, "支付"));
        orderList.add(new Order(2, "支付"));
        orderList.add(new Order(3, "支付"));
        orderList.add(new Order(1, "支付"));

        orderList.add(new Order(2, "发货"));
        orderList.add(new Order(4, "发货"));
        orderList.add(new Order(1, "发货"));
        orderList.add(new Order(3, "发货"));

        return orderList;
    }
}
